import React, { useState, useContext } from "react";
import { AppState } from "../App";
import { HeartIcon, DocumentTextIcon } from "@heroicons/react/solid";
import { FaLink, FaHandHoldingUsd } from "react-icons/fa";
import { ethers } from "ethers";
import axios from "axios";
import "../css/managerStyles.css";
import "../css/hualun.css";
import "../css/loader.css";

const Manager = () => {
  const App = useContext(AppState);
  const [Address, setAddress] = useState("");
  const [target, setTarget] = useState("");
  const [Description, setDescription] = useState("");
  const [moreDescription, setMoreDescription] = useState("");
  const [endTime, setEndTime] = useState("");
  const [PhotoHashes, setPhotoHashes] = useState([]);
  const [selectedImages, setSelectedImages] = useState([]);
  const [showDeleteButton, setShowDeleteButton] = useState(false);
  const [showImage, setShowImage] = useState({});
  const [loading, setLoading] = useState(false);
  const [tittle, setTittle] = useState("");
  const [errors, setErrors] = useState({});

  const validateForm = () => {
    let formErrors = {};
    if (!Address) formErrors.Address = "请输入收款人地址";
    if (!target) formErrors.target = "请输入目标金额";
    if (!tittle) formErrors.tittle = "请选择慈善类别";
    if (!Description) formErrors.Description = "请输入描述";
    if (!moreDescription) formErrors.moreDescription = "请输入额外描述";
    if (!endTime) formErrors.endTime = "请选择截至时间";
    if (selectedImages.length === 0) formErrors.selectedImages = "请上传图片";
    setErrors(formErrors);
    return Object.keys(formErrors).length === 0;
  };

  const handleImageChange = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      const files = Array.from(e.target.files);
      setSelectedImages((prevImages) => [...prevImages, ...files]);
      uploadImagesToPinata(files);
    }
  };

  const uploadImagesToPinata = async (files) => {
    setLoading(true);
    try {
      const uploadPromises = files.map(async (file) => {
        const formData = new FormData();
        formData.append("file", file);
        const response = await axios.post(
          "https://api.pinata.cloud/pinning/pinFileToIPFS",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
              Authorization:
              "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mb3JtYXRpb24iOnsiaWQiOiJjYjgzNmJjOS0xMjgzLTQwMWEtOWU4MS0wY2I5Y2ZkMjk1N2UiLCJlbWFpbCI6Imd1MDIwNDEyQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaW5fcG9saWN5Ijp7InJlZ2lvbnMiOlt7ImlkIjoiRlJBMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfSx7ImlkIjoiTllDMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfV0sInZlcnNpb24iOjF9LCJtZmFfZW5hYmxlZCI6ZmFsc2UsInN0YXR1cyI6IkFDVElWRSJ9LCJhdXRoZW50aWNhdGlvblR5cGUiOiJzY29wZWRLZXkiLCJzY29wZWRLZXlLZXkiOiJiZTNjOGVkY2IxZTA0MThkODlkMSIsInNjb3BlZEtleVNlY3JldCI6Ijc1OTVhY2JlY2E0MjU0YmM1ZGNlZTc3YTg2MTQwNGJkNGNjMmI0ZDM3ZGYwOTIwOTY0YjgxMzYzNjhhOGNiOGIiLCJpYXQiOjE3MTMxNTE2Nzh9.MgxXFGogmDXnIf6Z0U_qJlAuLcDxW3NFWwNr7u_u8Wc", // 替换为您的Pinata API密钥
            },
          }
        );
        return response.data.IpfsHash;
      });

      const hashes = await Promise.all(uploadPromises);
      setPhotoHashes((prevHashes) => [...prevHashes, ...hashes]);
    } catch (error) {
      console.error("Error uploading images to Pinata:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleMouseEnter = (index) => {
    setShowDeleteButton(true);
    setShowImage((prevState) => ({ ...prevState, [index]: true }));
  };

  const handleMouseLeave = (index) => {
    setShowDeleteButton(false);
    setShowImage((prevState) => ({ ...prevState, [index]: false }));
  };

  const handleDeleteImage = (index) => {
    const newSelectedImages = [...selectedImages];
    newSelectedImages.splice(index, 1);
    setSelectedImages(newSelectedImages);

    const newPhotoHashes = [...PhotoHashes];
    newPhotoHashes.splice(index, 1);
    setPhotoHashes(newPhotoHashes);
  };

  const handleImageClick = (index) => {
    setShowImage((prevState) => ({ ...prevState, [index]: !prevState[index] }));
  };

  const Create = async () => {
    if (validateForm()) {
      setLoading(true);
      try {
        if (!loading) {
          const tx = await App.Foundationcontract.createAdminRequest(
            tittle,
            Description,
            moreDescription,
            Address,
            ethers.utils.parseUnits(target, 0),
            PhotoHashes.join(","),
            Math.floor(new Date(endTime).getTime() / 1000) // 将日期转换为时间戳
          );
          await tx.wait();
          alert("创建成功!");
          setTittle("");
          setAddress("");
          setTarget("");
          setDescription("");
          setMoreDescription("");
          setEndTime("");
          setPhotoHashes([]);
          window.location.reload();
        }
      } catch (error) {
        if (
          error.message ===
          "MetaMask Tx Signature: User denied transaction signature."
        ) {
          alert("用户拒绝了交易签名。");
        } else if (
          error.message ===
          "execution reverted: Only manager can call this function"
        ) {
          alert("只有管理员可以调用此函数");
        } else {
          console.log(error.message);
          alert("发生错误: " + error.message);
        }
      } finally {
        setLoading(false);
      }
    } else {
      alert("请正确填写所有必填项");
    }
  };

  return (
    <>
      <div className="divFFF">
        {loading && <div className="loading-circle"></div>}
        <section>
          <div className="containerDiv">
            <div className="divThree">
              <p>这里是此慈善合约的管理员可以创建请求。</p>
            </div>
            <div className="divFour">
              <h1>爱心筹款</h1>
              <div className="divFO">
                <div className="divP1">
                  <div className="relative">
                    <HeartIcon className="input-icon" />
                    <input
                      placeholder="收款人地址"
                      value={Address}
                      onChange={(e) => setAddress(e.target.value)}
                      type="text"
                    />
                    {errors.Address && <span className="error">{errors.Address}</span>}
                  </div>
                </div>
                <div className="divP1">
                  <div className="relative">
                    <FaHandHoldingUsd className="input-icon" />
                    <input
                      placeholder="目标金额"
                      value={target}
                      onChange={(e) => setTarget(e.target.value)}
                      type="number"
                    />
                    {errors.target && <span className="error">{errors.target}</span>}
                  </div>
                </div>
                <div className="divP1">
                  <div className="relative">
                    <FaLink className="input-icon" />
                    <select
                      value={tittle}
                      onChange={(e) => setTittle(e.target.value)}
                      className="category-select"
                    >
                      <option value="">选择慈善类别</option>
                      <option value="教育资助">教育资助</option>
                      <option value="慈善救助">慈善救助</option>
                      <option value="环境保护">环境保护</option>
                      <option value="社会福利">社会福利</option>
                      <option value="文化艺术">文化艺术</option>
                    </select>
                    {errors.tittle && <span className="error">{errors.tittle}</span>}
                  </div>
                </div>
                <div className="divP1">
                  <div className="relative">
                    <DocumentTextIcon className="input-icon" />
                    <input
                      placeholder="描述"
                      value={Description}
                      onChange={(e) => setDescription(e.target.value)}
                      id="message"
                      type="text"
                    />
                    {errors.Description && <span className="error">{errors.Description}</span>}
                  </div>
                </div>
                <div className="divP1">
                  <div className="relative">
                    <DocumentTextIcon className="input-icon" />
                    <input
                      placeholder="额外描述"
                      value={moreDescription}
                      onChange={(e) => setMoreDescription(e.target.value)}
                      id="more-description"
                      type="text"
                    />
                    {errors.moreDescription && <span className="error">{errors.moreDescription}</span>}
                  </div>
                </div>
                <div className="divP1">
                  <div className="relative">
                    <DocumentTextIcon className="input-icon" />
                    <input
                      placeholder="截至时间 (YYYY-MM-DD HH:mm)"
                      value={endTime}
                      onChange={(e) => setEndTime(e.target.value)}
                      id="end-time"
                      type="datetime-local" // 修改这里
                    />
                    {errors.endTime && <span className="error">{errors.endTime}</span>}
                  </div>
                </div>

                <div className="divP1">
                  <div className="relative">
                    <FaLink className="input-icon" />
                    <input
                      type="file"
                      id="fileInput"
                      accept="image/*"
                      className="imgInput"
                      onChange={handleImageChange}
                      multiple
                    />
                    {errors.selectedImages && <span className="error">{errors.selectedImages}</span>}
                    {selectedImages.length > 0 && (
                      <div className="image-previews">
                        {selectedImages.map((image, index) => (
                          <div
                            key={index}
                            className="image-preview"
                            onMouseEnter={() => handleMouseEnter(index)}
                            onMouseLeave={() => handleMouseLeave(index)}
                          >
                            <p onClick={() => handleImageClick(index)}>
                              当前选择的图片: {image.name}
                            </p>
                            {showImage[index] && (
                              <div className="image-preview">
                                <img
                                  src={URL.createObjectURL(image)}
                                  alt="Preview"
                                  className="preview-img"
                                />
                                <button
                                  onClick={() => handleDeleteImage(index)}
                                  className="delete-button"
                                >
                                  删除
                                </button>
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
                <div className="p-2 w-full">
                  <button
                    onClick={Create}
                    className="flex mx-auto text-white bg-yellow-500 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded text-lg"
                  >
                    提交
                  </button>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </>
  );
};

export default Manager;
